
import pymongo  # pymong == 3.12.1
from com.util.loggingUtil import Logs
from com.util.configUtil import Conf

class MongoUtil:

    def __init__(self, collection_name=None, dbconfName="go-online"):
        Logs().info('com.util.MongoUtil init')
        MONGO_HOST = Conf.MONGO_CONF.getConfVal(dbconfName, "host")
        MONGO_PORT = int(Conf.MONGO_CONF.getConfVal(dbconfName, "port"))
        MONGO_NAME = Conf.MONGO_CONF.getConfVal(dbconfName, "name")
        MONGO_PASSWORD = Conf.MONGO_CONF.getConfVal(dbconfName, "password")
        MONGO_DB = Conf.MONGO_CONF.getConfVal(dbconfName, "mongodb")

        self.client = pymongo.MongoClient(host=MONGO_HOST, port=MONGO_PORT)
        self.client[MONGO_DB].authenticate(MONGO_NAME, MONGO_PASSWORD)
        self.db = self.client[MONGO_DB]
        self.col = self.db[collection_name]

    def find_one(self, query: dict):
        return self.col.find_one(query)

    def find_many(self, query: dict) -> list:
        return list(self.col.find(query))

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.client.close()
